package com.baijiaoxi.common.utils.jdk;

import com.baijiaoxi.common.model.base.CommonError;
import com.baijiaoxi.common.model.base.CoreException;
import lombok.extern.slf4j.Slf4j;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

@Slf4j
public class Sha1Util {
    public static String toSha1(String originStr) {
        log.debug("原始字符串:{}", originStr);
        return toSha1(originStr.getBytes());
    }

    public static String toSha1(byte[] messageBytes) {
        try {
            // 创建MessageDigest对象，指定使用SHA1算法
            MessageDigest digest = MessageDigest.getInstance("SHA1");

            // 计算消息的散列值
            byte[] hashBytes = digest.digest(messageBytes);

            // 将散列值转换为十六进制字符串
            StringBuilder hashString = new StringBuilder();
            for (byte b : hashBytes) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hashString.append('0');
                }
                hashString.append(hex);
            }
            return hashString.toString();
        } catch (NoSuchAlgorithmException e) {
            throw CoreException.create(CommonError.encryptionFail, e, "sha1");
        }
    }
}
